/**
 * 
 */
package viewcomponents;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.swing.JComponent;
import javax.swing.JPanel;

import model.turtle.Position;
import model.turtle.Turtle;
import view.Observer;

/**
 * 
 */
public class DemoCanvas extends JComponent implements Observer
{
	private List<Turtle> turtles;
	private Dimension mySize;
	private static final double dimension = 20;
	private int[] x;
	private int[] y;

	public DemoCanvas()
	{
		setBackground(Color.WHITE);
		setVisible(true);
		mySize = new Dimension(600, 600);
		setPreferredSize(mySize);
		x = new int[3];
		y = new int[3];
	}

	public void update(List<Turtle> turtles)
	{
		this.turtles = turtles;
		repaint();
	}

	@Override
	public void paint(Graphics g)
	{
		if (turtles == null)
			return;

		for (Turtle turtle : turtles)
		{
			List<Position> trail = turtle.getTrail();
			if (trail.size() == 0)
				return;

			Iterator<Position> it = trail.iterator();
			Position swap = it.next();
			while (it.hasNext())
			{
				Position tmp = it.next();
				g.drawLine(mySize.width / 2 + (int) swap.x, mySize.height / 2
						- (int) swap.y, mySize.width / 2 + (int) tmp.x,
						mySize.height / 2 - (int) tmp.y);
				swap = tmp;
			}

			Position p = turtle.getPosition();
			x[0] = (int) (mySize.width / 2 + p.x + Math.cos(-p.getDirection()
					* Math.PI / 180)
					* dimension);
			y[0] = (int) (mySize.height / 2 - p.y + Math.sin(-p.getDirection()
					* Math.PI / 180)
					* dimension);
			x[1] = (int) (mySize.width / 2 + p.x + Math.cos(-p.getDirection()
					* Math.PI / 180 + 2.35619)
					* dimension / 2);
			y[1] = (int) (mySize.height / 2 - p.y + Math.sin(-p.getDirection()
					* Math.PI / 180 + 2.35619)
					* dimension / 2);
			x[2] = (int) (mySize.width / 2 + p.x + Math.cos(-p.getDirection()
					* Math.PI / 180 - 2.35619)
					* dimension / 2);
			y[2] = (int) (mySize.height / 2 - p.y + Math.sin(-p.getDirection()
					* Math.PI / 180 - 2.35619)
					* dimension / 2);
			g.drawPolygon(x, y, 3);
		}
	}
}
